package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.annotation.RequiresPermissionsDesc;
import com.qf.pojo.DtsAdmin;
import com.qf.service.AdminAdminService;
import com.qf.service.DtsAdminService;
import com.qf.util.ResponseUtil;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;


@RestController
@CrossOrigin
@RequestMapping("/admin/admin")
public class AdminAdminController {

    @Autowired
    private AdminAdminService adminAdminService;

    @Autowired
    private DtsAdminService dtsAdminService;

    @GetMapping("list")
    public Object adminList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer limit,
            String username,String sort,String order
    ){
        IPage<DtsAdmin> iPage = adminAdminService.selectList(page,limit,username,sort,order);

        List<DtsAdmin> adminList = iPage.getRecords();
        long total = iPage.getTotal();
        HashMap<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", adminList);
        return ResponseUtil.ok(data);
    }

    //管理员添加
    @RequestMapping("/create")
    @RequiresPermissions("admin:admin:create")
    @RequiresPermissionsDesc(menu = "管理员",button = "管理员添加")
    public Object adminCreate(@RequestBody DtsAdmin dtsAdmin, HttpServletRequest request){

        String localAddr = request.getLocalAddr();
        String remoteAddr = request.getRemoteAddr();

        //密码加密
        Md5Hash md5Hash = new Md5Hash(dtsAdmin.getPassword(),dtsAdmin.getUsername(),1024);
        dtsAdmin.setPassword(md5Hash.toString());
        dtsAdmin = dtsAdminService.create(dtsAdmin);
        return ResponseUtil.ok(dtsAdmin);
    }

    //管理员修改
    @RequestMapping("/update")
    @RequiresPermissions("admin:admin:update")
    @RequiresPermissionsDesc(menu = "管理员",button = "管理员修改")
    public Object adminUpdate(@RequestBody DtsAdmin dtsAdmin){

        Md5Hash md5Hash = new Md5Hash(dtsAdmin.getPassword(), dtsAdmin.getUsername(), 1024);
        dtsAdmin.setPassword(md5Hash.toString());
        dtsAdminService.updateAdmin(dtsAdmin);
        return ResponseUtil.ok(dtsAdmin);
    }

    //删除管理员  逻辑删除
    @RequestMapping("/delete")
    @RequiresPermissions("admin:admin:delete")
    @RequiresPermissionsDesc(menu = "管理员",button = "管理员删除")
    public Object adminDelete(@RequestBody DtsAdmin dtsAdmin){

        DtsAdmin dtsAdmin1 = new DtsAdmin();
        dtsAdmin1.setId(dtsAdmin.getId());
        dtsAdmin1.setDeleted(true);
        dtsAdminService.updateAdmin(dtsAdmin1);
        return ResponseUtil.ok();
    }


}
